package com.drondea.testclient.handler.cmpp;

import cn.hutool.core.util.StrUtil;
import com.drondea.sms.message.cmpp.CmppSubmitResponseMessage;
import com.drondea.testclient.handler.AbstractSubmitResponseHandler;
import com.drondea.testclient.panel.CmppPanel;
import com.drondea.testclient.util.counter.CmppAtomicUtil;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;

/**
 * 测试收到的短信回应
 *
 * @author liuyanning
 */
@Sharable
@Slf4j
public class CmppSubmitResponseHandler extends AbstractSubmitResponseHandler<CmppSubmitResponseMessage> {
    private static final CmppPanel PANEL = CmppPanel.getInstance();

    @Override
    public void channelRead0(final ChannelHandlerContext ctx, CmppSubmitResponseMessage msg) {

        log.debug("CmppSubmitResponseMessage : {} : result: {} MsgId: {}", msg.getSequenceId(), msg.getResult(), msg.getMsgId());
        PANEL.responseCountLabel.setText(StrUtil.format("响应数量: {}", CmppAtomicUtil.RESPONSE_COUNT.incrementAndGet()));
        long result = msg.getResult();
        if (result == 0) {
            // 此处的状态只是短信提交结果，不代表实际发送是否成功,实际是否成功需要通过回执结果来判断
            PANEL.successCountLabel.setText(StrUtil.format("提交成功: {}", CmppAtomicUtil.SUCCESS_COUNT.incrementAndGet()));
        } else {
            PANEL.failCountLabel.setText(StrUtil.format("提交失败: {}", CmppAtomicUtil.FAIL_COUNT.incrementAndGet()));
        }

        // 当响应数量=发送数量时，设置结束时间
        if (CmppAtomicUtil.SEND_COUNT.get() == CmppAtomicUtil.RESPONSE_COUNT.get()) {
            // 计算平均提交速度
            calAvgSubmitSpeed(PANEL, CmppAtomicUtil.SEND_COUNT.get() - PANEL.submitCountBefSend);
        }
    }
    
}
